package array;
//螺旋矩阵
public class leetcode59 {
    public static void main(String[] args) {
        int n = 9;
        int[][] result = new int[n][n];
        result = generateMatrix(n);
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(result[i][j] + "\t");
            }
            System.out.print('\n');
        }
    }

    public static int[][] generateMatrix(int n){
        int[][] result = new int[n][n];
        int loop = 1;     //记录要循环几圈
        int offset = 1; //记录每圈每层打印的数量
        int number = 1; //记录要打印的数字
        int start_row=0, start_column=0;   //记录每一圈的起始点
        int row=0, column=0;   //记录答应的行列位置
        while(loop <= n/2){
            for(column = start_column; column < n - offset; column++){
                result[start_row][column] = number++;
            }

            for(row = start_row; row < n - offset; row++){
                result[row][column] = number++;
            }

            for(; column>start_column; column--){
                result[row][column] = number++;
            }


            for(; row>start_row; row--){
                result[row][column] = number++;
            }

            start_row++;
            start_column++;
            offset++;
            loop++;
        }
        if(n%2 == 1){
            result[n/2][n/2] = number;
        }
        return result;
    }
}
